from app.config import SQLALCHEMY_DATABASE_URI, MYSQL, SUPPER_USER
from app.config import ROLE_VIPUSER
from app.config import ROLE_USER
from app.config import ROLE_ADMIN
from app.config import ROLE_SUPER
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import IntegrityError

from sqlalchemy_utils import database_exists, create_database, table

_name
from app.models import Base, Admin, Adminlog, Comment, \
        Moviecol, Movie, Oplog, Preview, Role, Tag, User, \
            Userlog
            
from sqlalchemy import create_engine
engine = create_engine(
        SQLALCHEMY_DATABASE_URI,
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间，否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收（重置）
    )

# 数据库会话
def create_session():
    return sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = create_session()


def create_role(Role):
    rs = Role(name=ROLE_SUPER["name"], auth=ROLE_SUPER["auth"]) 
    ru = Role(name=ROLE_USER["name"], auth=ROLE_USER["auth"])
    rv = Role(name=ROLE_VIPUSER["name"], auth=ROLE_VIPUSER["auth"])
    ra = Role(name=ROLE_ADMIN["name"], auth=ROLE_ADMIN["auth"])
    
    Session = create_session()
    with Session() as s:

        s.add_all([rs, ru, rv, ra])
        s.commit()

def create_super(Admin, SUPPER_USER):
    su = Admin()
    su.register(nickname=SUPPER_USER['name'],
               email=SUPPER_USER['email'],
               password=SUPPER_USER['password'],
               role_id=SUPPER_USER["role_id"])


def init_role_su(Role, Admin, SUPPER_USER):
    try:
        create_role(Role)
        create_super(Admin, SUPPER_USER)
        print("role and super is created. [OK]")
    except IntegrityError:
        print("role and super is already. [OK]")

def initdb(): 
    
    if not database_exists(engine.url):
        print('make db')
        create_database(engine.url)             # 建库
        Base.metadata.create_all(engine)        # 建表     
    else:
        print("\ndb %s already exist![OK]"% MYSQL["DB"])  
        str = ''
        for k,v in Base.metadata.tables.items():
            str = str + k + " "
        print("\ntable : %s"% str)
    init_role_su(Role, Admin, SUPPER_USER)



if __name__ == '__main__':
    initdb()
